<?php
namespace app\client\controller;

use app\client\model\FreightTemplate as FreightTemplateModel;
use think\Cache;
use think\Request;
use think\Url;
use think\Db;
use think\Controller;
use think\Response;
use think\Loader;
use think\Session;

class FreightTemplate extends Controller
{
    /*
     * 运费模板列表
     */
    public function index()
    {
        $data = FreightTemplateModel::where(['member_id' => Session::get('shop_id')])->order(['id' => 'desc'])->select();
        return $this->fetch('index', [
            'mate_title' => '运费模板列表',
            'data'       => $data
        ]);
    }


    /*
     * 运费模板添加
     */
    public function create()
    {

        if (Request::instance()->isPost()) {


            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('FreightTemplate');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new FreightTemplateModel())->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('FreightTemplate/index'));
            }

            fail('操作失败');

        }

        $data = FreightTemplateModel::where(['member_id' => Session::get('shop_id')])->select();

        return $this->fetch('create', [
            "mate_title" => '运费模板添加',
            "area"       => Cache::get('province'),
            "data"       => twoArray($data)
        ]);

    }

    /*
     * 栏目删除
     */
    public function destroy($id)
    {

        if (FreightTemplateModel::destroy($id)) {
            win('删除成功', Url::build('FreightTemplate/index'));
        }

        fail('删除失败');

    }

    /*
     * 栏目编辑
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('FreightTemplate');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new FreightTemplateModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose) {
                win('操作成功', Url::build('FreightTemplate/index'));
            }

            fail('操作失败');

        }

        $item = FreightTemplateModel::get($id);
        $data = FreightTemplateModel::where(['member_id' => Session::get('shop_id'), 'id' => ['neq', $id]])->select();
        return $this->fetch('create', [
            "mate_title" => '运费模板编辑',
            "area"       => Cache::get('province'),
            "data"       => twoArray($data),
            'item'       => $item

        ]);
    }
}
